﻿#include "HttpPostLuogu.h"

#include <QDebug>
#include <QEventLoop>
#include <QJsonDocument>
#include <QNetworkRequest>
#include <QTimer>
#include <QUrl>

#include "QFile"
#include "QJsonArray"
#include "QUrlQuery"

HttpPostLuogu::HttpPostLuogu(QObject *parent)
    : QObject(parent)
    , manager(new QNetworkAccessManager(this))
{
}

QByteArray HttpPostLuogu::post(const QString &strUrl)
{
    lastError.clear();

    QUrl url(strUrl);

    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::UserAgentHeader,
                      "Codeforces API Client/1.0");
    request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);

    QEventLoop eventLoop;
    QTimer timer;

    timer.setSingleShot(true);
    QObject::connect(&timer, &QTimer::timeout, &eventLoop, &QEventLoop::quit);

    QNetworkReply *reply = manager->get(request);

    QObject::connect(reply, &QNetworkReply::finished, &eventLoop,
                     &QEventLoop::quit);

    timer.start(10000);

    eventLoop.exec();

    if (!timer.isActive())
    {
        lastError = "Request timeout";
        reply->abort();
        reply->deleteLater();
        return {};
    }
    timer.stop();

    if (reply->error() != QNetworkReply::NoError)
    {
        lastError = reply->errorString();
        reply->deleteLater();
        return {};
    }

    QByteArray responseData = reply->readAll();
    reply->deleteLater();
    return responseData;
}

QString HttpPostLuogu::getLastError() const { return lastError; }